import os
from pathlib import Path

import yaml
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings


# 嵌套模型定义
class DatabaseConfig(BaseModel):
    url: str
    pool_size: int = Field(default=5, ge=1)


class RedisConfig(BaseModel):
    url: str
    maxsize: int = 10


class MongoDBConfig(BaseModel):
    url: str
    maxsize: int = 10
    minsize: int = 3



class LoggingConfig(BaseModel):
    level: str = "INFO"
    dir: str = "./logs"


class ServerConfig(BaseModel):
    host: str = Field(default="0.0.0.0")
    port: int = Field(default=6379)
    debug: bool = True


class MysqlConfig(BaseModel):
    host: str
    port: int
    user: str
    password: str
    dbname: str


class TortoiseConfig(BaseModel):
    generate_schemas: bool = True


class EMAILConfig(BaseModel):
    smtp: str
    sender: str
    password: str
    port: int
    ssl: bool = True


class CodeConfig(BaseModel):
    expire: int = 60

class JWTConfig(BaseModel):
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

class AppConfig(BaseSettings):
    env: str = "dev"
    database: DatabaseConfig
    redis: RedisConfig
    mongodb: MongoDBConfig
    logging: LoggingConfig = LoggingConfig()
    server: ServerConfig = ServerConfig()
    mysql: MysqlConfig
    minsize: int = 1
    maxsize: int = 5
    tortoise: TortoiseConfig
    email: EMAILConfig
    code: CodeConfig
    jwt: JWTConfig

    @classmethod
    def from_yaml(cls, file_path: str):
        config_path = Path(file_path)
        if not config_path.exists():
            raise FileNotFoundError(f"配置文件 {file_path} 不存在")

        with open(config_path, "r", encoding="utf-8") as f:
            config_data = yaml.safe_load(f)

        return cls(**config_data)


env = os.getenv("ENV", "dev")
config = AppConfig.from_yaml(f"config.{env}.yml")
